﻿using Flurl.Http;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace bit.art.virtualtrade
{
    public partial class Form1 : Form
    {
        private static string filePath = "test.txt";
        public Form1()
        {
            InitializeComponent();
            label2.Text = $"{this.ClientSize.Height}-{this.Height}";

            Task.Run(() =>
            {
                Trade();
            });
        }
        
        public void Clear()
        {
            StreamWriter sr = new StreamWriter(filePath, false);
            sr.WriteLine(string.Empty);
            sr.Close();
        }

        public void Write(string msg)
        {
            StreamWriter sr = new StreamWriter(filePath, true);
            sr.WriteLine(msg);
            sr.Close();
        }

        protected override void OnMouseMove(MouseEventArgs e)
        {
            base.OnMouseMove(e);
            //var value = (decimal)(this.ClientSize.Height - e.Y) * 25 / 2000;
            var value = (decimal)(this.ClientSize.Height - e.Y) * 3.5m + 200;
            label1.Text = $"{value}";
            Write(label1.Text);
            //using (Graphics g = this.CreateGraphics())
            //{
            //    g.FillEllipse(Brushes.Cyan, e.X, e.Y, 10, 10);
            //}
        }

        protected override void OnMouseUp(MouseEventArgs e)
        {
            base.OnMouseUp(e);
            if (e.Button == MouseButtons.Right)
            {
                this.Refresh();
                Clear();
            }
        }

        private void Trade()
        {
            var market = "BTC/USDT";
            var buyUrl = "http://exapidev.586886.com/api/Market/BuyLimit";
            var sellUrl = "http://exapidev.586886.com/api/Market/SellLimit";

            //先读取数据
            var priceList = new List<decimal>();
            using (StreamReader sr = new StreamReader("test.txt", Encoding.Default))
            {
                string lineValue = "";
                do
                {
                    lineValue = sr.ReadLine();
                    decimal.TryParse(lineValue, out decimal price);
                    if (price > 0)
                    {
                        priceList.Add(price);
                        Console.WriteLine($"读取价格:{price}");
                    }
                }
                while (!string.IsNullOrEmpty(lineValue));
            }

            double minVolume = 0.001;//最低成交量
            double maxVolume = 2;//最高成交量
            var ran = new Random();

            Console.WriteLine($"价格数量：{priceList.Count}");

            //无限循环
            while (true)
            {
                foreach (var price in priceList)
                {
                    try
                    {
                        var accToken = GetToken();

                        //成交量随机
                        var volume = ran.NextDouble() * (maxVolume - minVolume);
                        volume += minVolume;

                        //用户2 下买单
                        var result1 = buyUrl
                            .WithHeader("Authorization", accToken)
                            .SetQueryParams(new
                            {
                                market,
                                price,
                                quantity = volume
                            })
                            .GetJsonAsync()
                            .Result;
                        Task.Delay(1000);

                        //用户1 下卖单
                        var result2 = sellUrl
                            .WithHeader("Authorization", accToken)
                            .SetQueryParams(new
                            {
                                market,
                                price,
                                quantity = volume
                            })
                            .GetJsonAsync()
                            .Result;

                        Console.WriteLine($"买单结果:{result1.result} 卖单结果:{result2.result} 价格：{price} 成交:{volume}");
                        label3.Text = $"买单结果:{result1.result} 卖单结果:{result2.result} 价格：{price} 成交:{volume}";
                        Thread.Sleep(15000);
                    }
                    catch { }
                }
            }
        }

        private string GetToken()
        {
            var url1 = "http://exapidev.586886.com/api/ThirdParty/GetAccessToken";
            var result1 = url1.PostJsonAsync(new
            {
                appId = "leyou",
                appSecret = "1eYou@8*93",
                scope = "partner"
            })
            .ReceiveJson()
            .Result;
            var token1 = $"Bearer {result1.result}";

            var url2 = "http://exapidev.586886.com/api/ThirdParty/GetEndUserAccessToken";
            var result2 = url2
                .WithHeader("Authorization", token1)
                .PostJsonAsync(new
                {
                    username = "shiyimin",
                    password = "Pass123$",
                    scope = "market"
                })
                .ReceiveJson()
                .Result;

            var token2 = $"Bearer {result2.result}";
            return token2;
        }
    }
}
